package com.tanhua.sso.service;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.tanhua.sso.config.AliyunSMSConfig;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

/**
 * 短信服务
 */
@Service
public class SmsService {

    @Autowired
    private AliyunSMSConfig aliyunSMSConfig;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送验证码
     */
    public void sendCheckCode(String mobile) {
        String redisKey = "CHECK_CODE_" + mobile;
        // String code = this.sendSms(mobile);        // 注释掉真正的发送验证码，便于开发测试
        String code = "123456";                      // 模拟发送验证码，设定为123456
        //发送验证码成功
        //将验证码存储到Redis，120秒后失效
        this.redisTemplate.opsForValue().set(redisKey, code, Duration.ofSeconds(120));
    }

    /**
     * 发送短信验证码
     */
    public String sendSms(String mobile) {
        DefaultProfile profile = DefaultProfile.getProfile(this.aliyunSMSConfig.getRegionId(), this.aliyunSMSConfig.getAccessKeyId(), this.aliyunSMSConfig.getAccessKeySecret());
        IAcsClient client = new DefaultAcsClient(profile);
        String code = RandomUtils.nextInt(100000, 999999) + "";
        CommonRequest request = new CommonRequest();

        request.setSysMethod(MethodType.POST);
        request.setSysDomain(this.aliyunSMSConfig.getDomain());
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        request.putQueryParameter("RegionId", this.aliyunSMSConfig.getRegionId());
        request.putQueryParameter("PhoneNumbers", mobile); //目标手机号
        request.putQueryParameter("SignName", this.aliyunSMSConfig.getSignName()); //签名名称
        request.putQueryParameter("TemplateCode", this.aliyunSMSConfig.getTemplateCode()); //短信模板code
        request.putQueryParameter("TemplateParam", "{\"code\":\"" + code + "\"}");//模板中变量替换
        try {
            CommonResponse response = client.getCommonResponse(request);
            String data = response.getData();
            if (StringUtils.contains(data, "\"Message\":\"OK\"")) {
                return code;
            }
            System.err.println("发送短信验证码失败~ data = " + data);
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("发送短信验证码失败~ mobile = " + mobile);
        }
        return null;
    }
}
